<script lang="ts" setup>
  import appStore from '@/store'
  import aliases, { aliasMsg, CreateAli, modifyAlias } from '@/api/aliases'
  import { reactive, ref, toRefs, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import FleetsService from '@/api/fleetsService'
  import { ElMessage, ElMessageBox, FormRules, FormInstance } from 'element-plus'
  const route = useRoute()
  const router = useRouter()
  const alias_id = route.params.id
  const props = defineProps({
    refashList: Number
  })
  const { refashList } = toRefs(props)
  watch(
    () => refashList?.value,
    (n) => {
      getAliasesList()
    }
  )
  const param = reactive({
    data: {
      project_id: appStore.userStore.project_id,
      offset: 1,
      limit: 10,
      fleet_id: '',
      url: '',
      policy_id: '',
      alias_id: '',
      UpdateAliasRequestBody: {
        associated_fleets: [
          {
            fleet_id: '',
            weight: '0'
          }
        ]
      }
    }
  })
  const tipData = reactive({
    project_id: appStore.userStore.project_id,
    offset: 0,
    limit: 10,
    fleet_id: '',
    autoScaling: {
      name: '',
      policy_type: '',
      target_based_configuration: {
        metric_name: '',
        target_value: 0
      }
    }
  })
  let tableTotal = ref(0)
  interface apiData {
    weight?: number
    isEdit?: boolean
  }
  let tableData: apiData[] = reactive([])
  // 获取表格数据
  let obj = reactive({} as { [key: string]: any })
  let tableAll = reactive({} as { [key: string]: any })
  let weightData: { data: { [key: string]: number } } = reactive({ data: {} })
  const getAliasesList = async () => {
    let res = await aliases.getAliasesList(param.data, {})
    tableData.length = 0
    tableAll = res.data.aliases
    tableAll.forEach((item: any) => {
      if (item.alias_id == alias_id) {
        obj = item
        tableData.push(...item.associated_fleets)
        emit('myClick', tableData)
      }
    })
    tableTotal.value = tableData.length
    weightData.data = {
      sdf126413: 0.1,
      derfag: 0.2
    }
    getFleets()
  }
  getAliasesList()
  const emit = defineEmits(['myClick'])
  const small = ref(false)
  const disabled = ref(false)
  const background = ref(true)
  const dialogVisible = ref(false)
  let aliasValue = ref('')
  interface optionList {
    value: string
    label: string
    disabled: boolean
  }
  const assRef = ref<FormInstance>()
  let fleetOptions: optionList[] = reactive([])
  const changeFleet = (fleet: string) => {
    tipData.fleet_id = fleet
  }
  let userType = ref()
  userType.value = localStorage.getItem('UserType') as string
  const getFleets = async () => {
    let res = await FleetsService.getFleets(tipData)
    let storage: optionList[] = reactive([])
    if (res.status == 200) {
      res.data.fleets.forEach((item: any) => {
        const itemJson = tableData.find((task: any) => item.fleet_id === task.fleet_id)
        storage.push({
          label: `${item.name}`,
          value: item.fleet_id,
          disabled: itemJson ? true : false
        })
      })
    }
    fleetOptions = storage
  }
  const handleSizeChange = (val: number) => {
    param.data.limit = val
    param.data.offset = 1
    getAliasesList()
  }
  const handleCurrentChange = (val: number) => {
    param.data.offset = val
    getAliasesList()
  }
  const formModel = reactive<{
    weight: ''
  }>({
    weight: ''
  })
  const rules = reactive<FormRules>({
    weight: [
      { required: true, message: '请输入权重', trigger: 'blur' },
      { pattern: /^([1-9]?\d|100)$/, message: '请输入0-100之间的整数(包含0和100)' }
    ]
  })
  let createBuild: CreateAli = {
    name: '',
    description: '',
    type: '',
    message: '',
    associated_fleets: []
  }
  let submitApp: modifyAlias = {
    project_id: appStore.userStore.project_id,
    alias_id: `${route.params.id}`,
    UpdateAliasRequestBody: JSON.parse(JSON.stringify(createBuild))
  }
  const toDetails = (id: string, name: string) => {
    router.push({ name: 'fleetDetails', params: { id, name } })
  }
  const deleteAs = (fleet_id: string, index: number, fleet_name: string) => {
    ElMessageBox.confirm(`确认删除此条数据？\n名称: ${fleet_name}\nFleetID: ${fleet_id} `, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      obj.associated_fleets.splice(index, 1)
      onSubmit(0, 0, 'delete')
    })
  }
  // 修改
  const changeWeight = (row: any) => {
    sessionStorage.setItem('oldWeight', row.weight)
    tableData.forEach((item) => {
      if (item.weight != row.weight) {
        item.isEdit = false
      }
    })
    row.isEdit = true
  }
  const params = reactive({
    resconfig: {
      weight: ''
    }
  })
  // 保存
  const onSubmit = async (row: any, index: any, type: any) => {
    params.resconfig = JSON.parse(JSON.stringify(row))
    if (type == 'save') {
      let weight = new RegExp(/^\d+(\.\d{1,3})?$/)
      if (param.data.UpdateAliasRequestBody.associated_fleets[0].weight) {
        let result = weight.test(param.data.UpdateAliasRequestBody.associated_fleets[0].weight)
        if (!result) {
          ElMessage({
            message: '请填写正确的权重值',
            type: 'warning'
          })
          return false
        }
      }
      obj.associated_fleets.forEach((item: any) => {
        item.weight = item.weight * 1
      })
    }
    submitApp.alias_id = alias_id as string
    submitApp.UpdateAliasRequestBody = JSON.parse(JSON.stringify(obj))
    try {
      let res = await aliases.updateAlias(submitApp)
      if (res.status < 300) {
        emit('myClick', tableData)
        ElMessage({
          message: type === 'save' ? '修改成功' : '删除成功',
          type: 'success'
        })
        getAliasesList()
      }
    } catch (err) {
      ElMessage({
        message: type === 'save' ? '修改失败' : '删除失败',
        type: 'error'
      })
    }
  }
  const dialogVisibtn = async () => {
    let revise = false
    tableData.forEach((ite: any) => {
      if (ite.isEdit == true) {
        revise = true
      }
    })
    if (revise) {
      ElMessage({
        message: '请先将修改的数据保存',
        type: 'warning'
      })
    } else {
      aliasValue.value = ''
      formModel.weight = ''
      dialogVisible.value = true
    }
  }
  // 创建
  const reviseDataset = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        let as: any = {
          associated_fleets: []
        }
        if (aliasValue.value.length > 0 && formModel.weight.length > 0) {
          let aliasData = {
            fleet_id: aliasValue.value,
            weight: Number(formModel.weight)
          }
          tableAll.forEach((item: any) => {
            if (item.alias_id == alias_id) {
              as = JSON.parse(JSON.stringify(item))
            }
          })
          as.associated_fleets.push(aliasData)
          submitApp.alias_id = alias_id as string
          submitApp.UpdateAliasRequestBody = JSON.parse(JSON.stringify(as))
          try {
            let res = await aliases.updateAlias(submitApp)
            if (res.status < 300) {
              ElMessage({
                message: '创建成功',
                type: 'success'
              })
              getAliasesList()
              dialogVisible.value = false
            }
          } catch (err) {
            ElMessage.error('创建失败')
          }
        }
      }
    })
  }
  // 取消
  const closeRow = async (row: any) => {
    if (sessionStorage.getItem('oldWeight') !== 'null') {
      row.weight = sessionStorage.getItem('oldWeight')
    }
    row.isEdit = false
  }
</script>
<template>
  <div id="aliasManager">
    <div class="insert-top">
      <div class="titles">关联Fleet</div>
      <button class="btn" @click="dialogVisibtn()" v-if="userType >= 5">新增关联</button>
    </div>
    <div class="table-box">
      <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#f4f5f8', color: '#252b3a' }" :border="true">
        <el-table-column label="Fleet名称/ID" class-name="elcell" width="260">
          <template #default="scope">
            <div class="toDetails" @click="toDetails(scope.row.fleet_id, scope.row.name)">
              {{ scope.row.name }}
            </div>
            <el-tooltip effect="dark" :content="scope.row.fleet_id" placement="bottom">
              <div class="id-box">
                {{ scope.row.fleet_id }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态">
          <template #default="scope">
            {{ scope.row.state ? $t('alias.' + scope.row.state) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="instance_count" label="实例数量"> </el-table-column>
        <el-table-column prop="process_count" label="进程数量" />
        <el-table-column prop="server_session_count" label="会话数量" />
        <el-table-column prop="max_server_session_count" label="最大会话数量" />
        <el-table-column prop="weight" label="权重">
          <template #default="scope">
            <div class="id-box" v-if="!scope.row.isEdit">
              {{ scope.row.weight }}
            </div>
            <div class="change" v-else>
              <el-input
                v-model="scope.row.weight"
                oninput="value=value.replace(/[^\d]/g,'');if(value>100){value=''};if(value.indexOf(0)==0){value=0}"
                placeholder="输入0-100之间的整数"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" v-if="userType >= 5">
          <template #default="scope">
            <div v-if="!scope.row.isEdit" class="actions-box">
              <div class="actions-details" @click="changeWeight(scope.row)">修改</div>
              <div class="line"></div>
              <div class="actions-delete" @click="deleteAs(scope.row.fleet_id, scope.$index, scope.row.name)">删除</div>
            </div>
            <div v-else class="actions-box">
              <div class="actions-details" @click="onSubmit(scope.row, scope.$index, 'save')">保存</div>
              <div class="line"></div>
              <div class="actions-details" @click="closeRow(scope.row)">取消</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增关联弹框 -->
    <el-dialog title="新增关联Fleet" v-model="dialogVisible" width="500px" center>
      <el-form :model="formModel" ref="assRef">
        <el-form-item prop="fleet_id">
          <template #label>
            <div class="item-label">Fleet ID</div>
            <el-tooltip effect="dark" placement="right" content="应用进程队列的id"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="aliasValue" class="m-2 fleet" placeholder="请选择fleet" @change="changeFleet">
            <el-option v-for="item in fleetOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
              <div class="fleetLabel">{{ item.label }}</div>
              <div class="fleetValue">{{ item.value }}</div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="weight" :rules="rules.weight">
          <template #label>
            <div class="item-label">权重</div>
            <el-tooltip effect="dark" placement="right" content="0-100之间的整数(包含0和100)"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-input type="text" v-model="formModel.weight"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="reviseDataset(assRef)">创建</el-button>
          </span>
        </span>
      </template>
    </el-dialog>
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="param.data.offset"
        v-model:page-size="param.data.limit"
        :page-sizes="[10, 20, 50, 100]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>
<style lang="scss" scoped>
  @import '@/assets/scss/dropdownBox.scss';
  #aliasManager {
    background-color: $blank-color;
    padding: 0;
    .insert-top {
      padding-bottom: 30px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .titles {
        font-size: 14px;
        font-weight: bold;
        color: #252b3a;
        margin-bottom: 0;
      }
      .btn {
        width: 100px;
        height: 30px;
      }
    }
    .el-dialog .el-form-item {
      flex-direction: column;
      align-items: flex-start;
    }
    .el-select {
      width: 400px;
    }
    .dialog-footer button:first-child {
      margin-right: 10px;
    }
    :deep(.el-input__wrapper) {
      width: 380px;
    }
    .dialog-enter-active {
      transition: all 0.3s ease;
    }

    .dialog-leave-active {
      transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
    }

    .dialog-enter,
    .dialog-leave-to {
      transform: translateX(10px);
      opacity: 0;
    }
    :deep(.el-input) {
      height: 28px;
      line-height: 28px;
      .el-input__wrapper {
        border-radius: 2px;
      }
      .el-input__inner {
        height: 28px;
        line-height: 28px;
      }
    }

    .search-box {
      display: flex;
      margin: 20px 0;
      align-items: center;
      .run-select {
        width: 160px;
        margin-right: 20px;
      }
    }
    .table-box {
      border-radius: 2px;
    }
    .demo-pagination-block {
      margin-top: 20px;
      position: relative;
      .el-pagination {
        justify-content: flex-end;
      }
      :deep(.el-pagination__total) {
        position: absolute;
        left: 0;
      }
      :deep(.el-pagination__sizes) {
        position: absolute;
        left: 58px;
      }
      :deep(.btn-next) {
        min-width: 28px;
        height: 28px;
        background: $blank-color;
        border: 1px solid $border-color;
        color: $text-color;
      }
      :deep(.btn-next:hover) {
        background: $bac-color;
      }
      :deep(.btn-prev) {
        min-width: 28px;
        height: 28px;
        background: $blank-color;
        border: 1px solid $border-color;
        color: $text-color;
      }
      :deep(.btn-prev:hover) {
        background: $bac-color;
      }
      :deep(.el-pager) {
        li {
          padding: 0;
          min-width: 28px;
        }
        .number,
        .more {
          height: 28px;
          background: $blank-color;
          border: 1px solid $border-color;
          color: $text-color;
        }
        .number:hover,
        .more:hover {
          background: $bac-color;
        }
        .is-active {
          border-color: $main-color;
          color: $main-color;
          background: $bac-color;
          font-weight: normal;
        }
      }
    }
    :deep(.id-box) {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .change {
      width: 170px;
    }
    .el-icon {
      margin-left: 10px;
      margin-top: -4px;
      color: #b4b6be;
    }
    :deep(.el-form-item__label) {
      display: inline-flex;
      align-items: center;
    }
    :deep(.el-table) {
      border-radius: 2px;
      font-size: 14px;
      color: $text-color;
      tr {
        border-color: $border-color;
        height: 78px;
      }
      thead > tr:first-child {
        height: 36px;
      }
      .el-table__cell {
        border-right: none;
      }
    }
    :deep(.toDetails) {
      color: $main-color;
      cursor: pointer;
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    :deep(.toDetails:hover) {
      text-decoration: underline;
    }
    :deep(.id-box) {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    :deep(.cell) {
      padding: 0 30px 0 20px;
    }
  }
</style>
